package com.yonyou.pmclouds.alter.rmiimpl;


import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.alter.entity.AlterListViewVO;
import com.yonyou.pmclouds.alter.entity.AlterVO;
import com.yonyou.pmclouds.alter.mapper.AlterMapper;
import com.yonyou.pmclouds.alter.rmiitf.AlterQuery;
import com.yonyou.pmclouds.altercategory.rmiitf.AlterCategoryQuery;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.SqlUtil;
import com.yonyou.pmclouds.discuss.itf.DiscussInternalOperation;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.projectpart.service.IProjectpartQryService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service(version = ApplicationConsts.APPLICATION_VERSION,interfaceClass= AlterQuery.class)
public class AlterQueryImpl implements AlterQuery , IPageQuerySerivce<AlterVO> {

    @Autowired
    private AlterMapper mapper;
    @Autowired
    private DiscussInternalOperation discussOperation;
    @Autowired
    private PictureRemoteService picService;
    @Autowired
    private ProjectSimpleQuery projectQuery;
    @Autowired
    private AlterCategoryQuery alterCategoryQuery;
    @Autowired
    private OrganizationQuery organizationQuery;
    @Autowired
    private IProjectpartQryService projectpartQryService;

    @Override
    public AlterListViewVO[] getAlterListInfo(String pkProject) throws BusinessException {
        if(StringUtils.isEmpty(pkProject)){
            return null;
        }
        AlterListViewVO[] result = mapper.getListViewVOByProject(pkProject);
        if(ArrayUtils.isEmpty(result)){
            return new AlterListViewVO[0];
        }
        setCategoryInfoForView(result);//类别参照信息
        getPictures(result);
        return result;
    }

    @Override
    public AlterVO getById(String pkAlter) throws BusinessException {
        if(StringUtils.isEmpty(pkAlter)){
            return null;
        }
        String[] pics = picService.queryPicNamesByPkEntity(pkAlter);  //查询图片
        AlterVO result = mapper.getById(pkAlter);
        if(result != null){
            result.setPictures(pics);
        }
        setRefInfo(result);   //项目参照信息
        setCategoryInfo(result);//类别参照信息
        projectpartQryService.fillProjectpartName(result);//工程部位
        return result;
    }

    @Override
    public boolean queryRefByIds(String code, String[] ids) throws BusinessException {
        if(StringUtils.isEmpty(code) || ArrayUtils.isEmpty(ids)){
            return false;
        }
        return mapper.getRefByIds(code, SqlUtil.getSqlIn(ids)) > 0;
    }

    /**
     * 添加照片
     */
    private void getPictures(AlterListViewVO[] vos) throws BusinessException {
        if(ArrayUtils.isEmpty(vos)) return;
        List<String> pkBills = new ArrayList<>();
        for(AlterListViewVO vo : vos){
            if(vo != null && vo.getPkAlter() != null) pkBills.add(vo.getPkAlter());
        }
        if(pkBills.size() == 0) return;

        Map<String, List<String> > picMap = picService.queryPicsByPkEntitys(pkBills.toArray(new String[0]));
        if(picMap == null) return;

        for(AlterListViewVO vo : vos){
            if(vo != null && picMap.get(vo.getPkAlter()) != null) vo.setPictures(picMap.get(vo.getPkAlter()).toArray(new String[0]));
        }
    }


    private void setRefInfo(AlterVO vo) throws BusinessException {
        // 项目
        ProjectVO projectVO = projectQuery.queryProject(vo.getPk_project());
        vo.setProjectName(projectVO.getSname());
        vo.setProjectCode(projectVO.getScode());

        String pkOrg = projectVO.getPkOrg();
        if(StringUtils.isNotEmpty(pkOrg)) {
            OrganizationVO organizationVO = organizationQuery.queryByPkSrc(RuntimeEnvironment.getTenantId(), pkOrg);
            vo.setOrgName(organizationVO==null?null:organizationVO.getSname());
        }
    }

    private void setCategoryInfoForView(AlterListViewVO[] vos) throws BusinessException {
        //签证类别
        String[] ids = null;
        for(AlterListViewVO vo : vos){
            if(StringUtils.isNotBlank(vo.getPkAltercategory())){
                ids = ArrayUtils.add(ids, vo.getPkAltercategory());
            }
        }
        //获取主键名字映射
        Map<String, String> categoryMap = alterCategoryQuery.queryNameByIds(ids);
        for(AlterListViewVO vo : vos){
            if(StringUtils.isNotBlank(vo.getPkAltercategory())){
                vo.setCategoryName(categoryMap.get(vo.getPkAltercategory()));
            }
        }
    }

    private void setCategoryInfo(AlterVO vo) throws BusinessException {
        if(StringUtils.isNotBlank(vo.getPkAltercategory())){
            //签证类别
            Map<String, String> categoryMap = alterCategoryQuery.queryNameByIds(new String[]{vo.getPkAltercategory()});
            vo.setCategoryName(categoryMap.get(vo.getPkAltercategory()));
        }
    }



    @Override
    public PageObject<Object> queryByCondition(String[] pkProjects, String[] creators, String startDate, String endDate, int[] billStatus, int pageStart, int pageSize) throws BusinessException {

        int count = mapper.countByCondition(null, pkProjects, creators, startDate, endDate, billStatus);

        AlterVO[] alterVOs = mapper.queryByCondition(pkProjects, creators, startDate, endDate, billStatus, pageStart, pageSize);

        return new PageObject<Object>(setRefFiledInfo(alterVOs),count,pageStart) ;
    }

    @Override
    public int countByCondition(String pkTenant, String[] pkProjects, String[] creators, String startDate, String endDate, int[] billStatus) throws BusinessException {
        return mapper.countByCondition(pkTenant, pkProjects, creators, startDate, endDate, billStatus);
    }

    /**
     * 处理参照字段，非必输项需校验空
     *
     * @param vos
     * @return
     * @throws BusinessException
     */
    private AlterVO[] setRefFiledInfo(AlterVO[] vos) throws BusinessException {
        if (ArrayUtils.isEmpty(vos)) {
            return new AlterVO[0];
        }

        Set<String> categorySet = new HashSet<String>();
        Set<String> projectSet = new HashSet<String>();
        Set<String> pkSet = new HashSet<String>();

        for (AlterVO vo:
                vos) {
            categorySet.add(vo.getPkAltercategory());
            projectSet.add(vo.getPk_project());
            pkSet.add(vo.getPkAlter());
        }

        Map<String,String>  categoryNameMap = alterCategoryQuery.queryNameByIds(categorySet.toArray(new String[0]));
        Map<String,ProjectVO> projectVOMap = projectQuery.queryProjects(projectSet.toArray(new String[0]));
        Map<String,List<String>> picMap = picService.queryPicsByPkEntitys(pkSet.toArray(new String[0]));

        for (AlterVO vo:
                vos) {
            vo.setProjectName(projectVOMap.get(vo.getPk_project()) == null ? null:projectVOMap.get(vo.getPk_project()).getSname());
            vo.setProjectCode(projectVOMap.get(vo.getPk_project()) == null ? null:projectVOMap.get(vo.getPk_project()).getScode());
            vo.setCategoryName(categoryNameMap.get(vo.getPkAltercategory()));
            vo.setPicNum(picMap.get(vo.getPkAlter()) == null ? 0 : picMap.get(vo.getPkAlter()).size());
        }

        return vos;
    }

    @Override
    public int countByProject(QueryListParam param) throws BusinessException{

        int count = mapper.countByCondition(null, new String[]{param.getPkProject()}, null, param.getStartDate(), param.getEndDate(), null);

        return count;
    }

    @Override
    public AlterVO[] queryByProject(QueryListParam param) throws BusinessException {
        AlterVO[] vos = mapper.queryByCondition(new String[]{param.getPkProject()}, null, param.getStartDate(), param.getEndDate(), null,param.getPageStart(),param.getPageSize());

        if(ArrayUtils.isEmpty(vos))
            return new AlterVO[0];

        setCategoryInfoForView(vos);//类别参照信息
        getPictures(vos);
        projectpartQryService.fillProjectpartName(vos);
        return vos;
    }

    /**
     * 添加照片
     */
    private void getPictures(AlterVO[] vos) throws BusinessException {
        if(ArrayUtils.isEmpty(vos)) return;
        List<String> pkBills = new ArrayList<>();
        for(AlterVO vo : vos){
            if(vo != null && vo.getPkAlter() != null) pkBills.add(vo.getPkAlter());
        }
        if(pkBills.size() == 0) return;

        Map<String, List<String> > picMap = picService.queryPicsByPkEntitys(pkBills.toArray(new String[0]));
        if(picMap == null) return;

        for(AlterVO vo : vos){
            if(vo != null && picMap.get(vo.getPkAlter()) != null) vo.setPictures(picMap.get(vo.getPkAlter()).toArray(new String[0]));
        }
    }

    private void setCategoryInfoForView(AlterVO[] vos) throws BusinessException {
        //签证类别
        String[] ids = null;
        for(AlterVO vo : vos){
            if(StringUtils.isNotBlank(vo.getPkAltercategory())){
                ids = ArrayUtils.add(ids, vo.getPkAltercategory());
            }
        }
        //获取主键名字映射
        Map<String, String> categoryMap = alterCategoryQuery.queryNameByIds(ids);
        for(AlterVO vo : vos){
            if(StringUtils.isNotBlank(vo.getPkAltercategory())){
                vo.setCategoryName(categoryMap.get(vo.getPkAltercategory()));
            }
        }
    }
    @Override
    public String getBillType() {
        return BillTypeConst.ALTER_BILLTYPE;
    }
}
